import os
import re

def create_new_node_list(queue_node_list):
    new_node_list = []
    for i in queue_node_list:
        node_list = i.split("-")
        if(len(node_list) == 2):
            for k in range(int(node_list[0]), int(node_list[1])+1):
                new_node_list.append(k)
        else:
            new_node_list.append(int(node_list[0]))
    return new_node_list

def remove_unwanted_chars(s):
    return re.sub('[^0-9-]', '', s)

def get_slurm_free_nodes(myconfig):
    subinfo = myconfig["subinfo"]
    nodeinfo = subinfo["nodeinfo"]

    tmp_queue_node_list = os.popen("sinfo | awk \'$1==\"{0}\" && $5==\"idle\" {{print $6}}\'".format(subinfo["queue"])).readlines()[0].strip("\n")
    # queue_node_list = os.popen("sinfo | awk \'$1==\"" + subinfo["queue"] + "\" && $5==\"idle\" {print $6}\'").readlines()[0].strip("\n")
    # queue_node_list = queue_node_list.strip("cn")
    # queue_node_list = queue_node_list.strip("[]")
    tmp_queue_node_list = tmp_queue_node_list.split(",")
    queue_node_list = []
    for i in tmp_queue_node_list:
        queue_node_list.append(remove_unwanted_chars(i))
    # #Test
    # #TODO:need to delete
    # queue_node_list = ['7670', '7694', '7791', '7794-8103', '8119-8122', '8209-8211', '8213-8214', '8225', '8253', '8255', '8258', '8266-8267', '8280-8282', '8296-8297', '8299-8339', '8358-8359', '8398-8399', '8408-8613', '8626-8679', '8686-8719', '8721-8879', '8881', '8888-8918', '9009-9026', '9134-9156', '9226-9271', '9325-9759', '9761-9781', '9788', '9804-9826', '9833-9847', '9888-9939', '10158-10208', '10215-10247', '10255-10256', '10263', '10280-10295', '10310-10311', '10357-10359', '10368-10390', '10455', '10461-10510', '10520-10775', '10994-11045', '11052-11084', '11140-11141', '11143', '11181-11283', '11285-11291', '11300-11331', '11337-11342', '11349-11388', '11399', '11408-11424', '11426-11439', '11448', '11452-11645', '11647', '11651', '11653-11654', '11666', '11668-11874', '11899', '11927-11928', '11945-11963', '11971-12037', '12070-12170', '12182-12263', '12273-12274', '12281-12282', '12285', '12287']
    
    free_node = create_new_node_list(queue_node_list)

    if nodeinfo["specify_node_list"] is not None:
        free_node += nodeinfo["specify_node_list"]
    else:
        if(len(free_node)*28 < subinfo["processinfo"]["np_end"]):
            if nodeinfo["specify_node_list"] is not None:
                free_node += nodeinfo["specify_node_list"]
                free_node = free_node.sort() 
    
    if nodeinfo["excluded_nodes_list"] is not None:
        # 取余集
        free_node = list(set(free_node).difference(set(nodeinfo["excluded_nodes_list"])))
    if(len(free_node)*28 < subinfo["processinfo"]["np_end"] and nodeinfo["node_list_order"] != "normal"):
        print("You need num of nodes is too many!")
        exit(0)
    else:
        subinfo["nodeinfo"]["free_nodes"] = free_node    
    return